package com.it135.citytraffic.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.it135.citytraffic.mapper.SurveyMapper;
import com.it135.citytraffic.pojo.entity.Survey;
import com.it135.citytraffic.pojo.vo.SurveyVO;
import com.it135.citytraffic.service.ISurveyService;
import lombok.RequiredArgsConstructor;
import lombok.extern.log4j.Log4j;
import lombok.extern.log4j.Log4j2;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;


@Service
@RequiredArgsConstructor
@Primary
@Log4j2
public class SurveyServiceImpl extends ServiceImpl<SurveyMapper, Survey> implements ISurveyService {

    private final SurveyMapper surveyMapper;

    /**
     * 新增调查问卷填写信息
     *
     * @param surveyList
     */
    @Override
    public void save(List<Survey> surveyList) {
        //保存
        for (Survey survey : surveyList) {
            //时间
            survey.setCreateTime(LocalDateTime.now());
            surveyMapper.save(survey);
        }
    }

    /**
     * 统计每个问题选项次数
     *
     * @return
     */
    @Override
    public String queryCount() {
        //获取问题名称
        List<String> questionList = surveyMapper.getQuestionName();
        HashMap<String, Integer> hm = new HashMap<>();
        StringBuilder sb = new StringBuilder();
        for (String question : questionList) {
            //跳过性别问题
            if (question.equals("2.您的性别是？")) {continue;}
            List<String> answerList = surveyMapper.getAnswer(question);
            if (question.charAt(0) > '9' || question.charAt(0) < '0') {//数字开头
                question = "1." + question;
            }
            //添加问题
            sb.append(question).append("<br>");
            for (String answer : answerList) {//遍历答案
                //单选项
                if (answer.split("; ").length == 1) {
                    if (hm.containsKey(answer)) {
                        hm.put(answer, hm.get(answer) + 1);
                    } else {//新增
                        hm.put(answer, 1);
                    }
                } else {
                    //含有多个选项
                    sb.append(answer).append("<br>");
                    String[] str = answer.split("; ");
                    for (String s : str) {
                        if (hm.containsKey(s)) {
                            hm.put(s, hm.get(s) + 1);
                        } else {
                            hm.put(s, 1);
                        }
                    }
                }
            }
            //统计
            Set<Map.Entry<String, Integer>> entries = hm.entrySet();
            for (Map.Entry<String, Integer> entry : entries) {
                //跳过无用的选项
                String answer = entry.getKey();
                if (answer.contains("其他") || ("无").equals(answer)
                        || ("wu").equals(answer) || ("暂无").equals(answer)
                        || ("不知道").equals(answer) || answer.contains("原神")
                        || ("都是米哈游干的").equals(answer) || ("飞行器出行").equals(answer)
                        || ("不清楚").equals(answer) || ("都行").equals(answer)
                        || answer.contains("没") || ("1").equals(answer)) {continue;}

                String[] parts = answer.split(". ");
                Integer cnt = entry.getValue();
                if (parts.length > 1) {
                    sb.append(parts[1]).append(" 被选择的次数是: ").append(cnt).append("<br>");
                } else {
                    sb.append(answer).append(" 被选择的次数是: ").append(cnt).append("<br>");
                }
            }
            hm.clear();
        }

        return sb.toString();
    }

    /**
     * 词云
     * @return
     */
    @Override
    public SurveyVO queryWordCloud() {
        //获取答案
        List<String> answer_one = surveyMapper.getAnswer(Survey.QUESTION_ONE);
        List<String> answer_two = surveyMapper.getAnswer(Survey.QUESTION_TWO);
        HashMap<String, Integer> wordCountMap = new HashMap<>();
        containsWord(answer_one, wordCountMap);
        containsWord(answer_two, wordCountMap);
        List<String> wordList = new ArrayList<>();
        List<Integer> countList = new ArrayList<>();
        List<Integer> values = new ArrayList<>(wordCountMap.values());
        Collections.sort(values);
        values.sort(Collections.reverseOrder());
        //筛选
        for (Integer integer : values) {
            if (integer >= 3) {countList.add(integer);}
        }
        String name;
        for (Integer frequency : countList) {
            //获取词
            for (String key : wordCountMap.keySet()) {
                if (wordCountMap.get(key).equals(frequency)) {

                    name = formatWord(key);
                    if (name == null) {continue;}
                    wordList.add(name);
                    wordCountMap.remove(key);
                    break;
                }
            }
        }

        //返回
        return SurveyVO.builder()
                .wordList(wordList)
                .count(countList)
                .build();
    }

    private String formatWord(String keyword) {
        switch (keyword) {//匹配
            case "管理": return "加强" + keyword;
            case "分流": return "进行" + keyword;
            case "停车": return "随意" + keyword;
            case "道路": return "拓展" + keyword;
            case "路线": return "多开发点" + keyword;
            case "公共交通": return "提倡" + keyword;
            case "遵守": return keyword + "交通规章制度";
            case "红绿灯": return "调整" + keyword + "时间";
            default: return null;
        }
    }

    /**
     * 统计词云次数
     * @param answer
     * @param hm
     */
    private void containsWord(List<String> answer, HashMap<String, Integer> hm) {
        for (String ao : answer) {//遍历答案
            for (String word : Survey.wordList) {//遍历关键词

                if(ao.contains(word) && !hm.containsKey(word)) {//添加
                    hm.put(word, 1);
                } else if (ao.contains(word) && hm.containsKey(word)) {
                    hm.put(word, hm.get(word) + 1);
                }
            }
        }
    }
}
